<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="720px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="formData.enterpriseName" placeholder="请输入企业名称" maxlength="100" show-word-limit />
      </el-form-item>

      <el-form-item label="企业简介" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="4" maxlength="2000" show-word-limit placeholder="请填写企业简介" />
      </el-form-item>

      <el-form-item label="企业福利" prop="benefits">
        <el-input v-model="formData.benefits" type="textarea" :rows="3" placeholder="请输入企业福利（逗号分隔，可选）" />
      </el-form-item>

      <el-form-item label="企业状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择企业状态">
          <el-option label="已认证" value="active" />
          <el-option label="待审核" value="pending" />
          <el-option label="已暂停" value="inactive" />
        </el-select>
      </el-form-item>

      <el-descriptions v-if="isEdit" :column="2" border>
        <el-descriptions-item label="企业编号">{{ formData.enterpriseId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="企业评分">{{ formData.rating ?? '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formData.createTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formData.updateTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { enterpriseAPI } from '@/api/enterprise'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  enterpriseData: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['update:modelValue', 'success', 'navigate'])

const visible = computed({ get: () => props.modelValue, set: (v) => emit('update:modelValue', v) })
const isEdit = computed(() => !!props.enterpriseData?.enterpriseId)

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑企业信息' : '新增企业')

const formRef = ref()
const loading = ref(false)

const formData = reactive({
  enterpriseId: '',
  enterpriseName: '',
  description: '',
  benefits: '',
  status: 'active',
  rating: '',
  createTime: '',
  updateTime: ''
})

const formRules = {
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度 2-100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入企业简介', trigger: 'blur' },
    { min: 10, max: 2000, message: '长度 10-2000 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择企业状态', trigger: 'change' }
  ]
}

watch(visible, (val) => { if (val) initForm() })

function initForm() {
  if (isEdit.value) {
    Object.keys(formData).forEach((k) => { formData[k] = props.enterpriseData?.[k] ?? formData[k] })
  } else {
    Object.keys(formData).forEach((k) => { formData[k] = (k === 'status') ? 'active' : '' })
  }
}

function handleClose() {
  visible.value = false
  formRef.value?.resetFields?.()
}


async function handleSubmit() {
  try {
    await formRef.value?.validate?.()
    loading.value = true
    
    // 准备提交数据
    const submitData = {
      enterpriseName: formData.enterpriseName,
      description: formData.description,
      benefits: formData.benefits,
      status: formData.status
    }
    
    console.log('准备提交的数据:', submitData)
    
    let result = null
    
    if (isEdit.value) {
      // 更新企业信息
      console.log('执行更新操作')
      result = await enterpriseAPI.updateEnterpriseInfo(formData.enterpriseId, submitData)
      console.log('更新返回的结果:', result)
      ElMessage.success('企业信息更新成功')
      // 更新formData以包含最新信息（result.data是后端返回的数据对象）
      Object.assign(formData, result?.data || submitData)
    } else {
      // 创建企业信息
      console.log('执行创建操作')
      result = await enterpriseAPI.createEnterprise(submitData)
      console.log('创建返回的完整结果:', result)
      console.log('result.code:', result.code)
      console.log('result.data:', result.data)
      console.log('result.data?.enterpriseId:', result.data?.enterpriseId)
      
      ElMessage.success('企业信息创建成功')
      
      // 使用服务器返回的完整数据
      const newEnterprise = result?.data || submitData
      console.log('新创建的企业数据:', newEnterprise)
      console.log('新数据的ID:', newEnterprise.enterpriseId)
      
      // 如果后端返回的data中已经有enterpriseId，直接使用
      if (newEnterprise.enterpriseId) {
        formData.enterpriseId = newEnterprise.enterpriseId
      }
      Object.assign(formData, newEnterprise)
    }
    
    console.log('最终要传递给父组件的数据:', formData)
    emit('success', formData)
    emit('navigate', 'enterprise-home') // 触发跳转到企业主页
    handleClose()
  } catch (error) {
    console.error('保存失败:', error)
    console.error('错误详情:', error.response)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer { text-align: right; }
.image-uploader { display: flex; flex-direction: column; gap: 8px; }
.upload-block { border: 1px dashed #dcdfe6; padding: 12px; border-radius: 6px; text-align: center; }
.preview { width: 160px; height: 160px; border-radius: 6px; border: 1px solid #ebeef5; }
.actions { margin-top: 8px; display: flex; gap: 8px; justify-content: center; }
.tip { color: #909399; font-size: 12px; margin-top: 6px; }
</style>

